package tk.hongbo.stream.coder

import android.graphics.*
import android.util.Log
import androidx.camera.core.ImageProxy
import tk.hongbo.stream.TAG
import java.io.ByteArrayOutputStream


/**
 * Created by HongboZhao on 2022/1/14.
 * @see <a href="https://blog.csdn.net/qq313629058/article/details/107209831">参考这里</a>
 */
object ImageHelper {

    fun getBitmap(image: ImageProxy): Bitmap? {
        val planes = image.planes[0].buffer
        val array = ByteArray(planes.remaining())
        planes.get(array, 0, array.size)
        image.close()
        return adjustPhotoRotation(BitmapFactory.decodeByteArray(array, 0, array.size), 90)
    }

    private fun adjustPhotoRotation(bm: Bitmap, orientationDegree: Int): Bitmap? {
        val m = Matrix()
        m.setRotate(orientationDegree.toFloat(), bm.width.toFloat() / 2, bm.height.toFloat() / 2)
        try {
            return Bitmap.createBitmap(bm, 0, 0, bm.width, bm.height, m, true)
        } catch (ex: OutOfMemoryError) {
        }
        return null
    }

    fun transImage(image: ImageProxy): ByteArray {
        val planes: Array<ImageProxy.PlaneProxy> = image.planes
        for (i in planes.indices) {
            Log.i(TAG, "pixelStride  " + planes[i].pixelStride)
            Log.i(TAG, "rowStride   " + planes[i].rowStride)
            Log.i(TAG, "width  " + image.width)
            Log.i(TAG, "height  " + image.height)
            Log.i(TAG, "Finished reading data from plane  $i")
        }

        //cameraX 获取yuv
        val yBuffer = planes[0].buffer
        val uBuffer = planes[1].buffer
        val vBuffer = planes[2].buffer
        val ySize = yBuffer.remaining()
        val uSize = uBuffer.remaining()
        val vSize = vBuffer.remaining()
        val nv21 = ByteArray(ySize + uSize + vSize)
        yBuffer[nv21, 0, ySize]
        vBuffer[nv21, ySize, vSize]
        uBuffer[nv21, ySize + vSize, uSize]

        //获取yuvImage
        val yuvImage = YuvImage(nv21, ImageFormat.NV21, image.width, image.height, null)
        //输出流
        val out = ByteArrayOutputStream()
        //压缩写入out
        yuvImage.compressToJpeg(Rect(0, 0, yuvImage.width, yuvImage.height), 100, out)
        //转数组
        image.close()
        return out.toByteArray()
    }
}